package com.estar.integaration.Controller;

import com.estar.integaration.Util.MExcelUtil;
import com.estar.integaration.Util.Util;
import com.estar.integaration.entity.NoSQL.Res;
import com.estar.integaration.entity.ProductMachineInfo;
import com.estar.integaration.entity.TechPushHistory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.*;

/**
 * Author: YJL
 * Date: 2022/1/19 8:51
 **/

@RestController
@RequestMapping("/inventory_ana")
public class InventoryAnalysis {

  @Value("${spring.profiles.active}")
  private String mEnvironment;

  @ResponseBody
  @PostMapping("import-excel")
  public Res getInventoryExcelFile(HttpServletRequest request){
    //取出文件 http
    MultipartHttpServletRequest params =  (MultipartHttpServletRequest)request;
    //TODO 拿文件类型
    List<MultipartFile> multipartFiles = params.getFiles("file");

    //紧急属性
    Boolean isUrgent =  params.getParameter("isUrgent" ).equals("isUrgent");
    Vector<String> multipartFilePath = new Vector<>();//上来的文件地址List
    String filePath = null;
    //插入历史记录的BatchList
    List<TechPushHistory> techPushHistoryList = new ArrayList<>();
    ProductMachineInfo productMachineInfo = null;
    Res returnRes = new Res();

    //取出文件写入本地，历史、地址信息 软记录
    for(MultipartFile file : multipartFiles){
      String UID = Util.getUUID();
      filePath = Util.writeFile2Local(file,mEnvironment,UID);
      //拿到文件
      multipartFilePath.add(filePath);
      //入历史List等待productId入db
      techPushHistoryList.add(new TechPushHistory(UID,file.getOriginalFilename(),new Timestamp(System.currentTimeMillis()),filePath,null,isUrgent));
    }
    //正式解析
    for(String address : multipartFilePath){
      //解析出所有文件
      String info = "";
      try {
//        productMachineInfo =  MExcelUtil.parseExcel(address, MaterialVo.class, MExcelUtil.initMaterialVOHash(),4,0,productDbService,materialService,info);
        //解析Excel
        productMachineInfo = MExcelUtil.HparseExcel(address);
      }catch (Exception e){
        e.printStackTrace();
        //自定义异常
        return new Res("40005",e.getMessage());
      }
      try {
      }catch (Exception e){
        //加入文件的未知错误
        return new Res("40003", "第" + String.valueOf(multipartFilePath.indexOf(address)+1) + "个文件出错");
      }
    }
    return returnRes;
  }

}
